import LoadingVue from '../../directive/TLoading/TLoading.vue'
import { createApp } from 'vue'
import { getZIndex } from '../../utils/utils'
import type { LoadingProps } from '../../directive/TLoading/TLoading.vue'

export interface GlobalLoadingProps extends LoadingProps {
  styles: { [key: string]: string }
  time: number
}

class TGlobalLoading {
  #props: Partial<GlobalLoadingProps> | undefined
  #loadingDom: HTMLElement | undefined
  #loadingTimer: ReturnType<typeof setInterval> | undefined

  constructor(props?: Partial<GlobalLoadingProps>) {
    this.#props = props
    this.#initLoading()
  }

  static #initLoadingStyle(): HTMLElement {
    const dom: HTMLElement = document.createElement('div')
    dom.id = 'ttt-global-loading'
    dom.style.position = 'fixed'
    dom.style.zIndex = String(getZIndex())
    dom.style.left = '0'
    dom.style.top = '0'
    dom.style.right = '0'
    dom.style.bottom = '0'
    return dom
  }

  #initLoading(): void {
    if (document.querySelector('#ttt-global-loading')) {
      this.#loadingDom = undefined
      document.querySelector('#ttt-global-loading')?.remove()
    }
    this.#loadingDom = TGlobalLoading.#initLoadingStyle()
    document.body.appendChild(this.#loadingDom)
    createApp(LoadingVue, this.#props).mount(this.#loadingDom)
    if (this.#props?.time) {
      if (this.#loadingTimer) clearTimeout(this.#loadingTimer)
      this.#loadingTimer = setTimeout(this.close, this.#props.time)
    }
  }

  public close(): void {
    if (this.#loadingDom) this.#loadingDom.remove()
  }
}

export const TLoading = (props?: Partial<GlobalLoadingProps>): TGlobalLoading => new TGlobalLoading(props)
